//
//  FunChoiceViewController.m
//  YinHang
//
//  Created by 张亚哲 on 14/10/25.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "FunChoiceViewController.h"
#import "GetFunChoiceList.h"
#import "FunChoiceList.h"



@interface FunChoiceViewController ()<UITableViewDataSource,UITableViewDelegate,FunChoiceDelegate,ASIHTTPRequestDelegate>{
    
    __weak IBOutlet UITableView *_tableView;
    NSMutableArray *arr;
    
    GetFunChoiceList *ChoiceService;
    
    NSMutableArray *state;//记录状态
    
    //参数
    MBProgressHUD *postHud;
    ASIFormDataRequest *getStateRequest;//获取状态
    ASIFormDataRequest *postStateRequest;//发送状态
    NSString *action;
    NSDictionary *paramsDict;
}

@end

@implementation FunChoiceViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //刷新
    
    [self getDate];
    [self setupRefresh];
    [_tableView headerBeginRefreshing];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //测试数据
    //arr = [NSMutableArray arrayWithObjects:@"on",@"on",@"1on",@"on",@"on",@"1on",@"on",@"3on",@"on",@"on",@"on",@"on",@"1on",@"on",@"on",@"1on",nil];
    arr = [NSMutableArray array];
    state = [NSMutableArray array];
//    for (int i = 0; i <= ChoiceService.pageInfo.dataArr.count + 1000; i++) {
//        //[arr addObject:[NSString stringWithFormat:@"%@",@"on"]];
//        arr[i] = @"on";
//    }
    
    self.navigationItem.title = @"功能选择";
    
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 30)];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = - 10;
    if (ios7) {
        self.navigationItem.leftBarButtonItems = @[negativeSpacer,leftBarButtonItem];
    }else{
        self.navigationItem.leftBarButtonItems = @[leftBarButtonItem];
    }
    
//    //添加
//    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//    addBtn.frame = CGRectMake(0, 0, 60, 35);
//    UIImage *postBtn_bgImg = [UIImage imageNamed:@"postbtn_bg"];
//    [addBtn setTitle:@"提交" forState:UIControlStateNormal];
//    [addBtn setTintColor:[UIColor whiteColor]];
//    [addBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [addBtn setBackgroundImage:[postBtn_bgImg stretchableImageWithLeftCapWidth:postBtn_bgImg.size.width*0.5f topCapHeight:postBtn_bgImg.size.height*0.5f] forState:UIControlStateNormal];
//    [addBtn addTarget:self action:@selector(add) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *addBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:addBtn];
//    self.navigationItem.rightBarButtonItem = addBarButtonItem;
    
    //tablerView
    // 屏幕适配
    //_tableView.frame = CGRectMake(_tableView.frame.origin.x, 64, _tableView.bounds.size.width,IPHONE5 ? 504: 416);
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.rowHeight = 60;

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark CustomMethod
//获取数据
-(void)getDate{
    ChoiceService = [[GetFunChoiceList alloc]init];
    //linkarr = linkService.pageInfo.dataArr;
    ChoiceService.delegate = self;
    [self getState];
}
//返回
-(void)back{
    ChoiceService = nil;
    [self.navigationController popViewControllerAnimated:YES];
}
//添加
-(void)add{
    
}

#pragma mark TableViewDelegate Method

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"funChoiceCell" owner:nil options:nil][0];
    }
    NSInteger row = indexPath.row;
    UIImageView *img = (UIImageView *)[cell.contentView viewWithTag:1];
    img.image = [UIImage imageNamed:@"u12.png"];
    //开关
    UISwitch *switch1 = (UISwitch *)[cell.contentView viewWithTag:4];
    switch1.tag = 10 + row;
    if ([arr[row][@"isok"] isEqualToString:@"1"]) {
        [switch1 setOn:YES];
    }else{
        [switch1 setOn:NO];
    }
    [switch1 addTarget:self action:@selector(click:) forControlEvents:UIControlEventValueChanged];
    //功能名称
    UILabel *funcName = (UILabel *)[cell.contentView viewWithTag:2];
    funcName.text = ChoiceService.pageInfo.dataArr[row][@"fname"];
    //
    UILabel *funcJf = (UILabel *)[cell.contentView viewWithTag:3];
    funcJf.text = [NSString stringWithFormat:@"(%@分)",ChoiceService.pageInfo.dataArr[row][@"fjifen"]];
    return cell;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (ChoiceService.pageInfo.dataArr.count != 0 && arr.count != 0) {
        return ChoiceService.pageInfo.dataArr.count;
    }else{
        return 0;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark IBAction Method

-(void)click:(id)sender{
    
    UISwitch *aa = sender;
    NSInteger row = aa.tag - 10;
    if ([arr[row][@"isok"] isEqualToString:@"1"]) {
        [arr[row] setValue:@"0" forKey:@"isok"];
        [aa setOn:NO];
        //[_tableView reloadData];
    }else{
        [arr[row] setValue:@"1" forKey:@"isok"];
        [aa setOn:YES];
        //[_tableView reloadData];
    }
    //aa.on = !aa.on;
    if (aa.on) {
        NSLog(@"%li",row);
    }
    [self postState:arr[row][@"fid"] state:arr[row][@"isok"]];
    
}

/**
 *  集成刷新控件
 */
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [_tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    /* 自动刷新(一进入程序就下拉刷新) */
    //[_tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_tableView addFooterWithTarget:self action:@selector(footerRereshing)];
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    // 刷新表格
    if (ChoiceService.isQuery ||![Constants isExistenceNetwork]) {
        [_tableView reloadData];
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_tableView headerEndRefreshing];
        return;
    }
    
    // 下拉刷新 （请求第一页数据）
    
    // 每次必须重置下 否则会数据混乱
    ChoiceService.pageInfo.pageno = @"1";
    [ChoiceService pageQuery];
}

- (void)footerRereshing
{
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
        // 刷新表格
        [_tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_tableView footerEndRefreshing];
        
        return;
    }
    
    // 如果正在查询 或 没有更多数据了
    //    NSLog(@"%i",linkService.isQuery);
    //    NSLog(@"%i",linkService.pageInfo.hasMoreData);
    if (ChoiceService.isQuery || !ChoiceService.pageInfo.hasMoreData) {
        // 2. 1秒后刷新表格UI
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
            [_tableView reloadData];
            
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [_tableView footerEndRefreshing];
            
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.labelText = @"没有更多数据了";
            [hud hide:YES afterDelay:1];
        });
        
        ChoiceService.pageInfo.hasMoreData = YES;
        
        return;
    }
    
    // 如果还有更多数据 请求下一页
    [ChoiceService.pageInfo nextPage];
    [ChoiceService pageQuery];
}
#pragma mark - QuestionService Delegate

- (void)didRecieveData{
    [_tableView headerEndRefreshing];
    [_tableView footerEndRefreshing];
    [_tableView reloadData];
}
- (void)didRecieveMsg{
    [_tableView headerEndRefreshing];
    [_tableView footerEndRefreshing];
    [_tableView reloadData];
}
//获取状态
-(void)getState{
    if (![Constants isExistenceNetwork]) {
        
    } else {
        if (!postHud || postHud.hidden == YES) {
            // 提示正在加载数据...
            postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            postHud.labelText = @"正在加载，请稍后...";
        }
        
        getStateRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
        getStateRequest.requestMethod = @"POST";
        // 设置超时时间
        getStateRequest.timeOutSeconds = 60;
        getStateRequest.delegate = self;
        // 设置参数
        action = @"FunctionSelectallisok";
        paramsDict = [NSDictionary dictionary];
        paramsDict = @{@"uid":UNAME};//uid会员名
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,paramsStr];
        
        NSData *paramsData = [result toGBKEncodingData];
        getStateRequest.postBody = [paramsData mutableCopy];
        
        [getStateRequest startAsynchronous];
    }
}

//修改状态
-(void)postState:(NSString *)fid state:(NSString *)stateStr{
    if (![Constants isExistenceNetwork]) {
        
    } else {
        if (!postHud || postHud.hidden == YES) {
            // 提示正在加载数据...
            postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            postHud.labelText = @"正在修改，请稍后...";
        }
        
        postStateRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
        postStateRequest.requestMethod = @"POST";
        // 设置超时时间
        postStateRequest.timeOutSeconds = 60;
        postStateRequest.delegate = self;
        // 设置参数
        action = @"FunctionSelectisok";
        paramsDict = [NSDictionary dictionary];
        paramsDict = @{@"uid":UNAME,@"fid":fid,@"isok":stateStr};//uid会员名
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,paramsStr];
        
        NSData *paramsData = [result toGBKEncodingData];
        postStateRequest.postBody = [paramsData mutableCopy];
        
        [postStateRequest startAsynchronous];
    }
}
#pragma mark - ASIHttpRequestDelegate method

- (void)requestFinished:(ASIHTTPRequest *)request {
    NSLog(@"%@",request.responseString);
    postHud.hidden = YES;
    NSError *err;
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
    
    // 1. 是否解析有错误
    if (!err) {
        
        // 2. 判断错误码
        NSInteger errorCode = [result[@"errorCode"]integerValue];
        
        if (errorCode == 0) {
            if (request == getStateRequest) {
                postHud.hidden = YES;
                NSDictionary *info = result[@"info"];
                state = info[@"data"];
                for (id dic in state) {
                    NSMutableDictionary *idcCopy = [dic mutableCopy];
                    [arr addObject:idcCopy];
                }
                [_tableView reloadData];//更新数据
            }else{
                postHud.hidden = YES;
                [SVProgressHUD showSuccessWithStatus:result[@"errorMsg"]];
            }
            
        }else{
            postHud.hidden = YES;
            if (request == postStateRequest) {
                
                [SVProgressHUD showSuccessWithStatus:result[@"errorMsg"]];
            }
        }
        
    } else {
        postHud.hidden = YES;
        [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request{
    postHud.hidden = YES;
    [SVProgressHUD showErrorWithStatus:@"服务器无法访问，请稍后再试!"];
}


-(void)dealloc{
    ChoiceService = nil;
    postHud = nil;
    [postStateRequest cancel];
    [getStateRequest cancel];
}

@end
